/*
 * DiskSpaceMonitor.cpp
 *
 *  Created on: 2017年3月7日
 *      Author: chuanjiang.zh
 */


#include "DiskSpaceMonitor.h"
#include "Path.h"
#include <stdio.h>


#ifdef WIN32
#else

#include <sys/statfs.h>

#endif //


#ifdef WIN32

bool DiskSpaceMonitor::getDiskSpace(const std::string& filepath, int64_t& totalSpace, int64_t& freeSpace)
{
	if (filepath.empty())
	{
		return false;
	}

	std::string dir(filepath);
	if (!comn::Path::isabs(dir))
	{
		comn::Path::abspath(dir);
	}

	dir.resize(3);

	ULARGE_INTEGER ulAvailable;
	ULARGE_INTEGER ulTotal;
	ULARGE_INTEGER ulFree;

	BOOL done = GetDiskFreeSpaceEx(dir.c_str(), &ulAvailable, &ulTotal, &ulFree);
	if (done)
	{
		totalSpace = ulTotal.QuadPart;
		freeSpace = ulAvailable.QuadPart;
	}
	return done != FALSE;
}


#else

bool DiskSpaceMonitor::getDiskSpace(const std::string& filepath, int64_t& totalSpace, int64_t& freeSpace)
{
	//printf("getDiskSpace. path:%s\n", filepath.c_str());
	
	bool found = false;
	struct statfs diskInfo;
	int rc = statfs(filepath.c_str(), &diskInfo);
		
	if (rc == 0)
	{
		int64_t blocksize = diskInfo.f_bsize;    //每个block里包含的字节数
		int64_t totalsize = blocksize * diskInfo.f_blocks;   //总的字节数，
		int64_t freeDisk = diskInfo.f_bfree * blocksize; //剩余空间的大小
		uint64_t availableDisk = diskInfo.f_bavail * blocksize;   //可用空间大小

		totalSpace = totalsize;
		freeSpace = availableDisk;
		
		found = true;
	}
	return found;
}


#endif //




